package com.huaxin.hxfiles.service.impl;

import com.huaxin.hxfiles.config.MinioConfig;
import com.huaxin.hxfiles.service.FileUploadService;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.http.Method;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * MINIO存储服务接口实现类
 *
 * @author
 * @date 2025/04/04
 */
public class MinioUploader implements FileUploadService {

    private final MinioClient minioClient;
    private final String bucketName;

    public MinioUploader(MinioClient minioClient, MinioConfig minioConfig) {
        this.minioClient = minioClient;
        this.bucketName = minioConfig.getBucketName();
    }

    @Override
    public void upload(String targetPath, String localFilePath) throws Exception {
        try (InputStream inputStream = Files.newInputStream(Paths.get(localFilePath))) {
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(targetPath).stream(
                                    inputStream, -1, 10485760)
                            .contentType("application/octet-stream")
                            .build());
        }
    }

    @Override
    public void upload(String targetPath, byte[] data) throws IOException {
        try (InputStream is = new ByteArrayInputStream(data)) {
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(targetPath)
                    .stream(is, data.length, -1)
                    .build();
            minioClient.putObject(args);
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    public boolean delete(String filePath) throws Exception {
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(filePath)
                        .build());
        return true;
    }

    @Override
    public String getDownloadUrl(String filePath) throws Exception {
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(filePath)
                        .expiry(86400)
                        .build());
    }
}